package sww.dto
{
	import flash.net.FileReference;
    import flash.events.IOErrorEvent;
    import flash.events.SecurityErrorEvent;
    import mx.events.CloseEvent;
    import mx.controls.Alert;

	public class FileIO
	{
		private var file:FileReference;
        
        /**
        *
        */
        private function init():void
        {                
            file = new FileReference();
            file.addEventListener(Event.SELECT, fileSelected);
            file.addEventListener(Event.COMPLETE, fileUploaded);
            file.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, uploadResult);
            file.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
            file.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
        }
            
        /**
        *
        */
        private function ioErrorHandler(e:IOErrorEvent):void
        {
            Alert.show(e.text);
        }
        
        /**
        *
        */    
        private function securityErrorHandler(e:SecurityErrorEvent):void
        {
            Alert.show(e.text);
        }

		/**
        *
        */
        public function uploadImage():void
        {
                //{description:"Images only, please", extension:"*.jpg;*.gif;*.png"}
                var filters:Array = new Array();
                filters.push(new FileFilter("image file","*.jpg;*.gif;*.png"));
                
                file.browse(filters);
        }
        
        /**
        *
        */    
        private function fileSelected(e:Event):void
        {
            Alert.show("Upload " + file.name + " ("+Math.round(file.size/1024)+"KB)?",
                       "Upload Confirmation",
                       Alert.YES|Alert.NO,
                       null,
                       proceedWithUpload);
        }
        
        /**
        *
        */    
        private function proceedWithUpload(e:CloseEvent):void
        {
            if (e.detail == Alert.YES)
            {
                var req:URLRequest = new URLRequest("upload.cfm");
                file.upload(req);
            }
        }
        
        /**
        *
        */    
        private function fileUploaded(e:Event):void
        {
            trace("upload completed");
        }
        
        /**
        *
        */    
        private function uploadResult(e:DataEvent):void
        {
            trace(e.data);
            newImage.load("getImage.cfm?fileName=" + e.data.toString());
        }
	 }
}